{extend name="common/base" /} {block name="body"}
<style type="text/css">
    html,
    body {
        height: 100%;
    }

    .upload,
    .layui-layer-content {
        height: 100%;
        background-color: #fff;
    }

    .layui-layer-header {
        padding: 10px 0 0 10px;
        overflow: hidden;
        height: 100%;
    }

    .layui-layer-content {
        padding: 10px 0;
        overflow: hidden;
    }

    .delete {
        color: red;
    }

    .delete:hover {
        color: red;
        border: 1px solid red;
    }

    .upload-group {
        height: 100%;
        overflow: auto;
    }

    .upload-group li {
        font-weight: 300;
        padding: 15px 25px;
        cursor: default;
        margin: 5px 10px 5px 0px;
    }

    .upload-group .active {
        background: rgba(48, 145, 242, 0.1);
        border-radius: 6px;
    }

    .group {
        position: relative;
    }

    .group i {
        display: none;
        color: #1E9FFF;
        position: absolute;
        margin-top: 3px;
    }

    .group:hover {
        background: rgba(48, 145, 242, 0.1);
        border-radius: 6px;
    }

    .group:hover i {
        display: inline-block;
    }

    .group-edit {
        left: 5px;
    }

    .group-del {
        right: 5px;
    }

    .header-action {
        position: absolute;
        height: 40px;
        width: 100%;
        z-index: 99999;
    }

    .footer-action {
        bottom: 10px;
        position: absolute;
        right: 20px;
        height: 40px;
    }

    .img-list {
        margin: 10px 0;
        position: absolute;
        overflow: auto;
        height: 100%;
        top: 40px;
        bottom: 40px;
    }

    .img-list-content {
        margin-bottom: 100px;
    }

    #upload {
        margin-right: 20px;
        float: right;
    }

    .preview {
        width: 130px;
        height: 130px;
        display: inline-block;
        text-align: center;
        position: relative;
        border: 1px solid #ccc;
        border-radius: 10px;
        margin-bottom: 5px;
        cursor: default;
        margin-right: 5px;
        background-color: #ccc;
    }

    .preview span {
        display: inline-block;
        height: 100%;
        vertical-align: middle;
    }

    .preview img {
        margin: 0 auto;
        vertical-align: middle;
        max-width: 120px;
        max-height: 120px;
    }

    .preview .mask {
        position: absolute;
        width: 130px;
        height: 130px;
        display: table-cell;
        margin: auto 0;
        background-color: rgba(0, 0, 0, 0.5);
        font-size: 18px;
        z-index: 9999;
        left: 0;
        display: none;
        border-radius: 10px;
    }

    .preview .mask .loading {
        display: none;
        margin-top: 50px;
    }

    .preview .mask .choose {
        display: none;
        margin-top: 20px;
        font-size: 50px;
        color: #fff;
    }

    .preview .success {
        display: none;
        position: absolute;
        left: 0;
        bottom: 0;
        z-index: 200;
        width: 100%;
        height: 100%;
        margin: auto 0;
        background: url(/theme/admin/static/img/success.png) no-repeat right bottom;
        background-size: 120px 40px;
        border-radius: 10px;
    }

    .preview .error {
        display: none;
        position: absolute;
        left: 0;
        bottom: 0;
        z-index: 200;
        width: 100%;
        height: 100%;
        margin: auto 0;
        background: url(/theme/admin/static/img/error.png) no-repeat right bottom;
        background-size: 120px 40px;
        border-radius: 10px;
    }

    .error_msg {
        background-color: rgba(0, 0, 0, 0.5);
        border-radius: 10px 10px 0 0;
        color: #fff;
        font-size: 14px;
        padding: 3px 1px;
    }

    .preview.success .success {
        display: inline-block;
    }

    .preview.error .error {
        display: inline-block;
    }

    .preview.loading .mask {
        display: inline-block;
    }

    .preview.loading .mask .loading {
        color: #fff;
        display: inline-block;
    }

    .preview.choose .mask {
        display: inline-block;
    }

    .preview.choose .mask .choose {
        display: inline-block;
    }

    .big_preview {
        font-size: 15px;
        top: 80%;
        position: absolute;
        left: 38%;
    }
</style>
<div class="upload">
    <div class="layui-layer-header layui-col-xs2">
        <ul class="upload-group">
            <li data-id="-1" class="group active">全部</li>
            <li data-id="0" class="group nogroup">未分组</li>
        </ul>
    </div>
    <div class="layui-layer-content layui-col-xs10">
        <div class="header-action">
            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm add-group">
                新增分组
            </button>
            <button type="button" data-name="移动至" class="layui-btn layui-btn-normal layui-btn-sm"
                    id="downpanel"></button>
            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm delete">
                <i class="layui-icon layui-icon-delete"></i>
            </button>
            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" id="upload"><i
                    class="layui-icon layui-icon-add-1"></i>上传图片
            </button>
        </div>
        <div class="img-list">
            <div class="img-list-content">
            </div>
        </div>
        <div class="file-list">
            <div class="file-list-content">

            </div>
        </div>
        <div class="footer-action">
            <button type="button" class="layui-btn layui-btn-normal layui-btn-sm submit">确定</button>
            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm cancel">取消</button>
        </div>
    </div>
</div>
{/block} {block name="my_js"}
<script>
    layui.use(['layer', 'plupload', 'btnGroup', 'notice', 'admin', 'flow'], function () {
        var $ = layui.jquery,
            btnGroup = layui.btnGroup,
            notice = layui.notice,
            layer = layui.layer,
            admin = layui.admin,
            plupload = layui.plupload;
        var group_id = 0;
        var btnOptions = {
            browse_button: 'downpanel',
            btn: {},
        };
        var img_id = '-1';
        var flow = layui.flow;
        var multipart_params = "{$upload.posts | raw | default = ''}";
        $('.cancel').click(function () {
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        });
        $('.delete').click(function () {
            var ids = [];
            $.each($('.preview.choose'), function (key, val) {
                ids.push($(this).attr('data-did'));
            });
            if (ids.length == 0) {
                return false;
            }
            admin.ajax('admin/upload/deletes', {
                ids: ids
            }, function (data) {
                if (data.code == 1001) {
                    $('.preview.choose').remove();
                    layer.msg(data.msg, {icon: 1});
                } else {
                    layer.msg(data.msg, {icon: 2});
                }
            }, '', 'post');
        });
        $('.submit').click(function () {
            var choose = $('.preview.choose');
            choose = choose.toArray().reverse();
            var preview = '{:input("preview")}';
            if (preview) {
                var input = '{:input("input")}';
                $.each(choose, function (key, val) {
                    var img = $(this).find('img').attr('src');
                    var val = $(this).attr('data-url');
                    $(preview, parent.document).attr('src', img);
                    $(input, parent.document).val(val);
                    var index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                    return false;
                });
                var index = parent.layer.getFrameIndex(window.name);
                parent.layer.close(index);
            }
            var func = '{:input("func")}';
            if (func) {
                parent[func](choose);
            }
        });

        //移动已选择图片到指定分组
        function move_group(gid) {
            var ids = [];
            $.each($('.preview.choose'), function (key, val) {
                ids.push($(this).attr('data-did'));
            });
            if (ids.length == 0) {
                return false;
            }
            if (gid == img_id) {
                layer.msg('文件已在当前分组', {icon: 2});
                return false;
            }
            admin.ajax('admin/upload/move/' + gid, {
                ids: ids
            }, function (data) {
                if (data.code == 1001) {
                    if (img_id != -1) {
                        $('.preview.choose').remove();
                    }
                    layer.msg(data.msg, {icon: 1});
                } else {
                    layer.msg(data.msg, {icon: 2});
                }
            }, '', 'post');
        }

        //加载图片
        function loadImg(clear) {
            if (typeof clear == 'undefined') {
                clear = false
            }
            if (clear) {
                $('.img-list-content').html('');
            }
            flow.load({
                elem: '.img-list-content' //指定列表容器
                , scrollElem: '.img-list'
                , isLazyimg: true
                , done: function (page, next) {
                    var lis = [];
                    admin.ajax('admin/upload?gid=' + img_id + '&page=' + page + '&limit=15', '', function (data) {
                        if (data.code == 1001) {
                            $.each(data.data, function (key, val) {
                                lis.push(addImage({
                                    preview: val.file_path_preview,
                                    d_id: val.d_id,
                                    status: ''
                                }, true));
                            });
                            var pages = Math.ceil(data.total / 15);
                            next(lis.join(''), page < pages);
                        }
                    }, '', 'get');
                }
            });
        }

        //选择左侧分组
        $('.upload-group').on('click', '.group', function () {
            $('.group').removeClass('active')
            $(this).addClass('active');
            img_id = $(this).attr('data-id');
            loadImg(true);
            var string = multipart_params + '&gid=' + img_id;
            plupload.setOption('multipart_params', admin.urlToJson(string.split('&')));
        });
        //新建分组
        $('.add-group').click(function () {
            layer.prompt({title: '请输入新建文件组名称', formType: 0}, function (text, index) {
                admin.ajax('admin/upload/group', {
                    name: text
                }, function (val) {
                    if (val.code == 1001) {
                        //更新左侧分组
                        addItem(val.data);
                        layer.msg(val.msg, {icon: 1});
                    } else {
                        layer.msg(val.msg, {icon: 2});
                    }
                });
                layer.close(index);
            });
        });
        init();
        img_id = '-1';
        loadImg(true);
        //初始化
        function init() {
            //加载文件组
            admin.ajax('admin/upload/group', '', function (val) {
                if (val.data) {
                    var data = val.data;
                    $.each(data, function (index, value) {
                        addItem(value);
                    })
                    btnOptions.btn = data
                    btnGroup.loader(btnOptions, function (id) {
                        move_group(id)
                    });
                }
            }, '', 'get');
        }

        //添加分组条目
        function addItem(value) {
            $('.upload-group').append('<li data-id="' + value.id + '" class="group">\n' +
                '<i class="layui-icon layui-icon-edit group-edit"></i>' + value.name + '\n' +
                '<i class="layui-icon layui-icon-close-fill group-del" ></i>\n' +
                '</li>');
            btnGroup.add(btnOptions, value);
        }

        //删除分组
        $('.upload-group').on('click', '.group-del', function () {
            deleteItem($(this).parent().attr('data-id'), $(this).parent());
        });

        //删除左侧、下拉按钮组条目
        function deleteItem(id, obj) {
            layer.confirm('确定删除该文件组？', {
                btn: ['确定', '取消'] //按钮
            }, function (index) {
                admin.ajax('admin/upload/group/' + id, '', function (data) {
                    if (data.code == 1001) {
                        layer.close(index);
                        layer.msg(data.msg, {icon: 1});
                        obj.remove();
                        btnGroup.del(btnOptions, id);
                    } else {
                        layer.msg(data.msg, {icon: 2});
                    }
                }, '', 'DELETE');
            });
        }


        var options = {
            browse_button: 'upload',
            max_file_size: "{$upload.upload_img_size}kb",
            filters: {
                mime_types: [
                    {title: "Image files", extensions: "{$upload.upload_img_ext}"},
                ]
            },
            url: '{$upload.url}',
            multipart_params: admin.urlToJson(multipart_params.split('&')),
            FilesAdded: function (uploader, files) {
                $('.img-list').scrollTop(0);
                $.each(files, function (ley, val) {
                    plupload.previewImage(val, function (image) {
                        addImage({
                            preview: image,
                            fileid: val.id,
                            status: 'loading'
                        });
                        uploadProgress(val.id, '0');
                    });
                })

                uploader.start()
            },
            FileUploaded: function (uploader, file, info) {
                var res = JSON.parse(info.response);
                if (info.status == 200) {
                    uploadSuccess(file.id, res.d_id, res.path);
                }
            },
            UploadProgress: function (uploader, file) {
                uploadProgress(file.id, file.percent);
            },
            Error: function (uploader, err) {
                notice.init({
                    type: 'danger',
                    autoClose: true,
                    title: "您选择的文件：" + err.file.name + "，" + err.message
                });
                uploadError(err.file.id);
            }
        };

        function uploadProgress(id, val) {
            $('.loading_' + id).html(val + "%");
        }

        function changeUploadStatus(id, status) {
            $('.status_' + id).removeClass('loading');
            $('.status_' + id).removeClass('error');
            $('.status_' + id).removeClass('success');
            $('.status_' + id).addClass(status);
        }

        function uploadSuccess(id, d_id, url) {
            $('.status_' + id).attr('data-did', d_id);
            $('.status_' + id).attr('data-url', url);
            changeUploadStatus(id, 'success');
        }

        function uploadError(id) {
            changeUploadStatus(id, 'error');
        }

        function addImage(options, is_list) {
            options.status = options.status || '';
            options.id = options.id || '';
            options.d_id = options.d_id || '';
            options.fileid = options.fileid || '';
            options.error_msg = options.error_msg || '';
            options.preview = options.preview || options.url;
            if (typeof is_list == 'undefined') {
                is_list = false;
            }
            var html = '<div class="preview ' + options.status + ' status_' + options.fileid + '" data-fileid="' + options.fileid + '" data-did="' + options.d_id + '">' +
                '<div class="mask">' +
                '<span class="choose">' +
                '<i class="layui-icon choose layui-icon-ok"></i>' + '</span>' +
                '<span class="loading loading_' + options.fileid + '"></span>' + '</div>' +
                '<div class="error">' + '<div class="error_msg"> ' + options.error_msg + ' </div>' +
                '</div>' +
                '<div class="success">' +
                '</div>';
            //<span class="big_preview">放大</span>
            //TODO: 预览放大
            if (is_list) {
                html += '<img lay-src="' + options.preview + '"><span></span>' +
                    '</div>';
                return html;
            } else {
                html += '<img src="' + options.preview + '"><span></span>' +
                    '</div>';
                $('.img-list-content').prepend(html);
            }
        }

        plupload.loader(options);
        $('.img-list-content').on("click", ".preview", function () {
            if ($(this).hasClass('loading')) {
                layer.msg('图片上传中', {icon: 2});
                return false;
            }
            if ($(this).hasClass('choose')) {
                $(this).removeClass('choose');
            } else {
                $(this).addClass('choose');
            }
        });

    });
</script>
{/block}